package com.kaige.usercenter.service.impl;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaige.usercenter.model.entity.User;
import com.kaige.usercenter.service.UserService;
import com.kaige.usercenter.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @author 18319
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-06-19 18:24:51
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 新用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 校验入参
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            return -1;
        }
        // 校验账户长度
        if (userAccount.length() < 4) {
            return -1;
        }
        // 校验账号是否包含特殊字符 使用hutool工具类
        String regex = "^[a-zA-Z0-9]+$";
        if (!ReUtil.isMatch(regex, userAccount)) {
            return -1;
        }
        // 校验密码长度
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            return -1;
        }
        // 校验两次密码是否一致
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 校验账户是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = count(queryWrapper);
        if (count > 0) {
            return -1;
        }
        // 对密码进行加密
        // 创建盐
        final String SALT = "kaige";
        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + SALT).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setPassword(encryptPassword);
        user.setIsValid(1);
        boolean save = save(user);
        if (!save) {
            return -1;
        }
        return user.getId();
    }
}




